import {
  indexApi
} from '../../../api/index';
import {
  request
} from '../../../utils/request';

Page({
  data: {
    defaultData: {
      title: "个人资料", // 导航栏标题
      imageSrc: "/images/back.png",
      isBackToPreviousPage: true
    },
    avatarUrl: '',
    showPopup: false,
    nickName: "",
    age: null
  },

  onLoad(options) {
    const {
      avatar,
      nickName
    } = options;
    console.log("nickName", nickName);
    this.setData({
      avatarUrl: avatar,
      nickName: nickName
    });
    console.log("nickName========", this.data.nickName);
  },

  onAvatarTap() {
    this.setData({
      showPopup: true
    });
  },

  onChooseAvatar(e) {
    console.log("e", e);
    const {
      avatarUrl
    } = e.detail;
    const file = {
      url: avatarUrl,
      size: 0 // 或者如果可以获取真实大小，则传递真实大小
    };
    this.uploadFile(file); // 直接上传
  },

  async uploadFile(file) {
    try {
      const uploadTask = wx.uploadFile({
        url: indexApi.upLoadApi(),
        header: {
          "Content-Type": "multipart/form-data"
        },
        filePath: file.url,
        name: 'file',
        formData: {},
        success: (res) => {
          const data = JSON.parse(res.data);
          console.log('Upload success', data);
          this.setData({
            avatarUrl: data.data // 设置上传后的头像 URL
          });
        },
        fail: (err) => {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        },
      });
    } catch (error) {
      wx.showToast({
        title: '上传失败,请联系管理员',
        icon: 'none'
      });
    }
  },


  //确认
  // 申请成为师傅
  async clickPerson() {
    const reqTemplate = {
      nickName: this.data.nickName,
      avatar: this.data.avatarUrl,
      age: this.data.age,
    }
    try {
      const res = await request({
        url: indexApi.updateUser(),
        method: "POST",
        data: reqTemplate
      });
      console.log(res);
      wx.setStorageSync('nickName', this.data.nickName);
      wx.switchTab({
        url: '/pages/usercenter/index',
      })

    } catch (error) {
      console.error("Error:", error);
    }
  },

  onNicknameInput(event) {
    console.log("event.detail", event.detail);
    this.setData({
      nickName: event.detail
    })

  },

  onAgeInput(event) {
    console.log("event.detail", event.detail);
    this.setData({
      age: event.detail
    })
  },




  toBack() {
    wx.navigateBack({
      delta: 1
    });
  }
})